import React, { useEffect, useRef, useState } from "react";
import { getAccountStat } from "@/services/order/order_api";
import { getCustomerInfo } from "@/services/customer/custom_api";
import {
  Card,
  Row,
  Col,
  Button,
  Space,
  Statistic,
  Divider,
  Typography,
  message,
} from "antd";
import { useIntl, useModel } from "@umijs/max";
import {
  DashboardOutlined,
  UserOutlined,
  ShoppingCartOutlined,
  PieChartOutlined,
  FileTextOutlined,
  BarChartOutlined,
  DollarOutlined,
  GlobalOutlined,
} from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { Chart } from "frappe-charts/dist/frappe-charts.min.esm";
import { CustomerDataVo } from "../constants";

const { Text } = Typography;

const BusinessDashboard = () => {
  const navigate = useNavigate();
  const intl = useIntl();
  const { initialState } = useModel("@@initialState");
  const { currentUser } = initialState || {};
  const [admin] = useState(currentUser?.isAdmin);
  const [accountInfo, setAccountInfo] = useState<CustomerDataVo>();

  const [loading, setLoading] = useState(false);
  const [todayStats, setTodayStats] = useState<any[]>([]);
  const [monthlyData, setMonthlyData] = useState<any[]>([]);

  const chartRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
   
    const fetchData = async () => {
      if (currentUser && !admin) {
        const response = await getCustomerInfo();
        if (response.code !== 0) {
          message.error(
            response.msg ||
              intl.formatMessage({
                id: "request.error.default",
                defaultMessage: "请求失败，请重试",
              })
          );
          return;
        }
        setAccountInfo(response.data);
      }
      try {
        setLoading(true);
        const response = await getAccountStat();
        if (response.code !== 0) {
          message.error(
            response.msg ||
              intl.formatMessage({
                id: "request.error.default",
                defaultMessage: "请求失败，请重试",
              })
          );
          return;
        }

        const todayStatsData = [
          {
            title: intl.formatMessage({
              id: "dashboard.todayStats.orders",
              defaultMessage: "今日订单数量",
            }),
            value: response.data.todayOrderCount,
            suffix: intl.formatMessage({
              id: "dashboard.unit.order",
              defaultMessage: "单",
            }),
            color: "#1890ff",
          },
          {
            title: intl.formatMessage({
              id: "dashboard.todayStats.returns",
              defaultMessage: "今日退单量",
            }),
            value: response.data.todayOrderCancel,
            suffix: intl.formatMessage({
              id: "dashboard.unit.order",
              defaultMessage: "单",
            }),
            color: "#9b0aeaff",
          },
          {
            title: intl.formatMessage({
              id: "dashboard.todayStats.issues",
              defaultMessage: "今日问题件",
            }),
            value: response.data.todayOrderAbnormal,
            suffix: intl.formatMessage({
              id: "dashboard.unit.order",
              defaultMessage: "单",
            }),
            color: "#f57207ff",
          },
        ];
        setTodayStats(todayStatsData);
        setMonthlyData(response.data.orderNumVoList);

        return response.data;
      } catch (error: any) {
        message.error(
          error.message ||
            intl.formatMessage({
              id: "request.error.default",
              defaultMessage: "请求失败，请重试",
            })
        );
        return false;
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  // ==== 快捷操作 ====
  const quickActions = admin
    ? [
        {
          icon: <UserOutlined />,
          name: intl.formatMessage({
            id: "dashboard.quickActions.customerManagement",
            defaultMessage: "客户管理",
          }),
          color: "#52c41a",
          path: "/custom/list",
        },
        {
          icon: <ShoppingCartOutlined />,
          name: intl.formatMessage({
            id: "dashboard.quickActions.orderList",
            defaultMessage: "订单列表",
          }),
          color: "#faad14",
          path: "/order/list",
        },
        {
          icon: <PieChartOutlined />,
          name: intl.formatMessage({
            id: "dashboard.quickActions.billList",
            defaultMessage: "账单列表",
          }),
          color: "#13c2c2",
          path: "/bill/list",
        },
        {
          icon: <FileTextOutlined />,
          name: intl.formatMessage({
            id: "dashboard.quickActions.productList",
            defaultMessage: "产品列表",
          }),
          color: "#722ed1",
          path: "/product/list",
        },
      ]
    : [
        {
          icon: <ShoppingCartOutlined />,
          name: intl.formatMessage({
            id: "dashboard.quickActions.orderList",
            defaultMessage: "订单列表",
          }),
          color: "#faad14",
          path: "/order/list",
        },
        {
          icon: <PieChartOutlined />,
          name: intl.formatMessage({
            id: "dashboard.quickActions.billList",
            defaultMessage: "账单列表",
          }),
          color: "#13c2c2",
          path: "/bill/list",
        },
      ];

  const handleQuickActionClick = (path: string) => {
    navigate(path);
  };

  // ==== 初始化折线图 ====
  useEffect(() => {
    if (!chartRef.current || monthlyData.length === 0) return;

    new Chart(chartRef.current, {
      title: intl.formatMessage({
        id: "dashboard.chart.title",
        defaultMessage: "近30天订单趋势",
      }),
      type: "line",
      height: 400,
      data: {
        labels: monthlyData.map((d) => d.displayDate),
        datasets: [
          {
            name: intl.formatMessage({
              id: "dashboard.chart.orders",
              defaultMessage: "订单数",
            }),
            values: monthlyData.map((d) => d.value),
            color: "#1890ff",
          },
        ],
      },
      tooltipOptions: {
        formatTooltipX: (label: string) => label,
        formatTooltipY: (value: number) =>
          `${value}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`),
      },
      lineOptions: {
        dotSize: 6,
        hideDots: false,
        hideLine: false,
        regionFill: 0,
      },
    });
  }, [monthlyData]);

  return (
    <div style={{ padding: 24 }}>
      {/* 上方区域 */}
      <Row gutter={16}>
        <Col xs={24} md={12} lg={10}>
          <Card
            title={
              <Space>
                <DashboardOutlined />
                <Text strong>
                  {intl.formatMessage({
                    id: "dashboard.quickActions.title",
                    defaultMessage: "快捷操作",
                  })}
                </Text>
              </Space>
            }
            bordered={false}
            headStyle={{ borderBottom: 0 }}
          >
            <div
              style={{
                display: "grid",
                gridTemplateColumns: "repeat(auto-fill, minmax(100px, 1fr))",
                gap: 14,
              }}
            >
              {quickActions.map((action, index) => (
                <Button
                  key={index}
                  type="text"
                  onClick={() => handleQuickActionClick(action.path)}
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                    justifyContent: "center",
                    height: 90,
                    padding: "16px 8px",
                    borderRadius: 8,
                    backgroundColor: `${action.color}10`,
                    border: `1px solid ${action.color}20`,
                  }}
                >
                  <div
                    style={{
                      width: 48,
                      height: 48,
                      borderRadius: "50%",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      backgroundColor: `${action.color}10`,
                      marginBottom: 12,
                      color: action.color,
                      fontSize: 20,
                    }}
                  >
                    {action.icon}
                  </div>
                  <Text strong style={{ color: action.color }}>
                    {action.name}
                  </Text>
                </Button>
              ))}
            </div>
          </Card>
        </Col>

        <Col xs={24} md={12} lg={14}>
          <Card
            title={
              <Space>
                <PieChartOutlined />
                <Text strong>
                  {intl.formatMessage({
                    id: "dashboard.todayStats.title",
                    defaultMessage: "今日业务数据",
                  })}
                </Text>
              </Space>
            }
            bordered={false}
            headStyle={{ borderBottom: 0 }}
          >
            <Row gutter={16}>
              {todayStats.map((stat, index) => (
                <Col xs={24} sm={12} md={12} lg={6} key={index}>
                  <Card
                    bordered={false}
                    bodyStyle={{
                      padding: "16px 0",
                      display: "flex",
                      alignItems: "center",
                    }}
                  >
                    <div
                      style={{
                        width: 48,
                        height: 48,
                        borderRadius: "50%",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        backgroundColor: `${stat.color}10`,
                        marginRight: 16,
                        color: stat.color,
                        fontSize: 20,
                      }}
                    >
                      {stat.icon || <BarChartOutlined />}
                    </div>
                    <Statistic
                      title={stat.title}
                      value={stat.value}
                      precision={stat.precision || 0}
                      suffix={stat.suffix}
                      valueStyle={{
                        color: stat.color,
                        fontSize: 20,
                        fontWeight: 600,
                      }}
                    />
                  </Card>
                </Col>
              ))}
            </Row>
          </Card>
        </Col>
      </Row>
      {!admin && (
        <>
          <Divider style={{ margin: "24px 0" }} />
          <Row gutter={16}>
            <Col span={24}>
              <Card
                title={
                  <Space>
                    <UserOutlined />
                    <Text strong>账号信息</Text>
                  </Space>
                }
                bordered={false}
                headStyle={{ borderBottom: 0 }}
              >
                <Row gutter={24}>
                  <Col xs={24} sm={8}>
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <div
                        style={{
                          width: 48,
                          height: 48,
                          borderRadius: "50%",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          backgroundColor: "#f0f7ff",
                          marginRight: 16,
                          color: "#1890ff",
                          fontSize: 20,
                        }}
                      >
                        <UserOutlined />
                      </div>
                      <div>
                        <div style={{ color: "#8c8c8c", fontSize: 14 }}>
                          账号名
                        </div>
                        <div style={{ fontSize: 18, fontWeight: 500 }}>
                          {accountInfo ? accountInfo.customerName : "--"}
                        </div>
                      </div>
                    </div>
                  </Col>

                  <Col xs={24} sm={8}>
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <div
                        style={{
                          width: 48,
                          height: 48,
                          borderRadius: "50%",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          backgroundColor: "#f6ffed",
                          marginRight: 16,
                          color: "#52c41a",
                          fontSize: 20,
                        }}
                      >
                        <DollarOutlined />
                      </div>
                      <div>
                        <div style={{ color: "#8c8c8c", fontSize: 14 }}>
                          账号余额
                        </div>
                        <div style={{ fontSize: 18, fontWeight: 500 }}>
                          {accountInfo ? accountInfo.customerBalance : "--"}
                        </div>
                      </div>
                    </div>
                  </Col>

                  <Col xs={24} sm={8}>
                    <div style={{ display: "flex", alignItems: "center" }}>
                      <div
                        style={{
                          width: 48,
                          height: 48,
                          borderRadius: "50%",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          backgroundColor: "#fff7e6",
                          marginRight: 16,
                          color: "#fa8c16",
                          fontSize: 20,
                        }}
                      >
                        <GlobalOutlined />
                      </div>
                      <div>
                        <div style={{ color: "#8c8c8c", fontSize: 14 }}>
                          结算币种
                        </div>
                        <div style={{ fontSize: 18, fontWeight: 500 }}>
                          {accountInfo ? accountInfo.customerCurrency : "--"}
                        </div>
                      </div>
                    </div>
                  </Col>
                </Row>
              </Card>
            </Col>
          </Row>
        </>
      )}

      <Divider style={{ margin: "24px 0" }} />

      {/* 下方折线图 */}
      <Card
        title={
          <Space>
            <BarChartOutlined />
            <Text strong>
              {intl.formatMessage({
                id: "dashboard.chart.title",
                defaultMessage: "近30天业务趋势",
              })}
            </Text>
          </Space>
        }
        bordered={false}
      >
        <div ref={chartRef} />
      </Card>
    </div>
  );
};

export default BusinessDashboard;
